package learn_concurrent._1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Tow phase termination 两阶段终止模式
public class T16 {
	public static void main(String[] args) throws InterruptedException {
		Monitor monitor = new Monitor();
		monitor.start();
		Thread.sleep(3000);
		monitor.stop();
	}
}

class Monitor {
	private final static Logger logger = LoggerFactory.getLogger(Monitor.class);
	
	private Thread thread;
	
	public Monitor() {
		this.thread = new Thread(() -> {
			while(true) {
				Thread current = Thread.currentThread();
				if(current.isInterrupted()) {
					doAfterWork();
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					System.out.println("-");
					current.interrupt();
				}
				doWork();
			}
		}, "Monitor-thread");
	}
	
	private void doWork() {
		logger.debug("执行监控工作");
	}

	private void doAfterWork() {
		logger.debug("执行善后工作");
	}

	public void start() {
		thread.start();
	}
	
	public void stop() {
		thread.interrupt();
	}
}

